<template>
	<jk-dialog
		v-model="showDialog"
		title="选择-物料"
		width="1000px"
		append-to-body
		@on-visible-change="onVisibleChange"
		@on-cancel="onVisibleChange(false)"
		@on-confirm="onConfirmBtn"
	>
		<header ref="box1" class="margin-bottom-10 flex-between-center">
			<el-button size="small" icon="el-icon-plus" @click="createDialogState = true">新增</el-button>
			<div class="flex-end-center">
				<!-- :disabled="categoryIdDisable" -->
				<el-cascader
					ref="tree"
					v-model="categoryIds"
					:options="treeData"
					class="search-bar-item-size3 item-gap"
					placeholder="物料分类"
					size="small"
					clearable
					:props="{
						value: 'id',
						label: 'name',
						checkStrictly: true
					}"
					@change="onMenuChange"
				></el-cascader>
				<!-- <el-select v-model="searchParams.typeNameOrCode" clearable placeholder="存货类型" size="small" class="search-bar-item-size3 item-gap" @clear="onSearchBtn" @change="onSearchBtn">
					<el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.code" />
				</el-select> -->
				<jk-search-input v-model="searchParams.nameOrCode" show-search class="search-bar-item-size3" placeholder="编号或名称" @clear="onSearchBtn" @on-search="onSearchBtn" @keyup.enter.native="onSearchBtn"></jk-search-input>
			</div>
		</header>

		<jk-table
			ref="jkTable"
			:radio-config="{trigger: 'row'}"
			:loading="tableLoading"
			class="width-100-percent"
			:data="tableData"
			border
			highlight-hover-row
			highlight-current-row
			:height="tableHeight - 100"
			:checkbox-config="{checkMethod: checkboxMethod}"
			@checkbox-change="selectChangeEvent"
		>
			<vxe-column type="checkbox" width="60" align="center"></vxe-column>
			<vxe-table-column field="code" title="编号" sortable :min-width="120" />
			<vxe-table-column field="name" title="名称" fixed :min-width="260"> </vxe-table-column>
			<vxe-table-column field="models" title="规格型号" fixed :min-width="120"> </vxe-table-column>
			<vxe-table-column field="categoryName" title="物料分类" min-width="80" />
			<vxe-table-column field="typeName" title="存货类型" min-width="90" />
			<vxe-column title="状态" align="center" field="auditState" :width="100">
				<template slot-scope="scope">
					<jk-common-status :status="scope.row.auditState"></jk-common-status>
				</template>
			</vxe-column>
			<vxe-table-column field="unitName" title="基准计量单位" min-width="100" />
		</jk-table>
		<footer ref="box2" class="flex-end-center margin-top-10">
			<jk-page
				:page-index="searchParams.pageNo"
				:page-sizes="searchParams.pageSizes"
				:page-size="searchParams.pageSize"
				:total="searchParams.count"
				layout="total, prev, pager, next"
				@on-change="onPageChange"
			/>
		</footer>
		<create-dialog
			:dialog-state="createDialogState"
			:select-tree-item="{
				id: ruleForm.categoryId,
				name: ruleForm.categoryName,
				code: ruleForm.categoryCode,
			}"
			@on-visible-change="onVisibleChangeOfCreateDialog"
			@on-finish="onFinishOfCreateDialog"
		></create-dialog>
	</jk-dialog>
</template>

<script>
    import calDialogHeight from '../../../../mixins/cal-table-height';
    import { createTree, pageConfig } from '../../../../utils/jk/jk-tool';
    import { spinProductPage } from '../../../../api/material/material';
    import { spinProductCategoryList } from '../../../../api/material/category';
    import { systemBusinessDictPage } from '../../../../api/basicData/businessDict';
    import createDialog from '../../../material/base/save-dialog';

    export default {
        components: {
            createDialog
        },
        mixins: [calDialogHeight],
        props: {
            dialogState: {
                type: Boolean,
                default: false
            },
            title: {
                type: String,
                default: '物料'
            },
            checkKeyName: {
                type: String,
                default: 'productId'
            },
            defaultSelectRows: {
                type: Array,
                default() {
                    return [];
                }
            },
            defaultCategory: { // 默认的物料分类
                type: [String, Number],
                default: ''
            },
            defaultStockType: { // 默认的存货类型
                type: String,
                default: ''
            },
            // categoryIdssssss: {
            //     type: Array,
            //     default: () => []
            // },
            ruleForm: {
                type: Object,
                default: () => {}
            }
        },
        data() {
            return {
                createDialogState: false,
                categoryIds: [],
                treeData: [],
                categoryIdDisable: false,
                searchParams: {
                    count: 0,
                    pageNo: pageConfig.pageNo,
                    pageSize: pageConfig.pageSize,
                    processId: null,
                    categoryId: null,
                    name: null,
                    // typeNameOrCode: '',
                    nameOrCode: '',
                    auditState: 1,
                    dictCategoryCode: 'STOCK_TYPE'
                },
                typeList: [],
                checkArr: [],
                selectRow: null,
                searchBarProcessId: null,
                tableData: [],
                showDialog: false,
                tableLoading: false,
                selectData: []
            };
        },
        methods: {
            onVisibleChangeOfCreateDialog(e) {
                this.createDialogState = e;
            },
            onFinishOfCreateDialog() {
                this.getListRequest();
                this.createDialogState = false;
            },
            onMenuChange(e) {
                if (e) {
                    this.$set(this.searchParams, 'categoryId', e[e.length - 1]);
                } else {
                    this.$set(this.searchParams, 'categoryId', null);
                }
                this.getListRequest();
            },
            selectChangeEvent({ records }) {
                this.checkArr = records.filter(x => !x._disabled).map(x => {
                    return x;
                });
            },
            checkboxMethod(e) {
                return !e.row._disabled;
            },
            onSearchBtn() {
                this.$set(this.searchParams, 'pageNo', 1);
                this.getListRequest();
            },
            onPageChange(e, size) {
                this.$set(this.searchParams, 'pageNo', e);
                this.$set(this.searchParams, 'pageSize', size);
                this.getListRequest();
            },
            onConfirmBtn() {
                if (this.checkArr.length) {
                    const arr = this.checkArr.filter(x => !x._disabled);
                    this.$emit('on-confirm', arr);
                } else {
                    this.$tipsBar(this, 'custom', 'warning', '请选择数据');
                }
            },
            setCheckState(arr) {
                arr.forEach((x) => {
                    x._disabled = false;
                    this.defaultSelectRows.forEach(k => {
                        if (x.id === k[this.checkKeyName]) {
                            x._disabled = true;
                        }
                    });
                });
                this.tableData = arr;
                this.tableData.forEach((x, index) => {
                    if (x._disabled) {
                        this.$refs.jkTable.$refs.xTable.setCheckboxRow([this.tableData[index], this.tableData[index]], true);
                    }
                });
            },
            getListRequest() {
                this.tableLoading = true;
                this.selectData = [];
                return spinProductPage(this.searchParams).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.searchParams.count = res.data.count;
                        this.setCheckState(res.data.res || []);
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                // if (!e) {
                //     // Object.assign(this.$data, this.$options.data());
                //     const rawData = this.$options.data.call(this); // 保持 this 上下文
                //     Object.keys(rawData).forEach(key => {
                //         this[key] = rawData[key];
                //     });
                // }
            },
            getTreeListRequest() {
                return spinProductCategoryList().then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res ? JSON.parse(JSON.stringify(res.data.res)) : [];
                        // if (this.defaultCategory) {
                        //     const ids = resData.find(x => x.name === this.defaultCategory) ? resData.find(x => x.name === this.defaultCategory).id : null;
                        //     this.$set(this.searchParams, 'categoryId', ids);
                        //     this.categoryIds = [ids];
                        //     console.log(ids, 'ids');
                        // }
                        this.treeData = createTree(resData, {});
                        // 如果传入了默认分类
                        if (this.defaultCategory) {
                            // 递归查找完整路径
                            const findCategoryPath = (data, targetCode, path = []) => {
                                for (const item of data) {
                                    const newPath = [...path, item.id];
                                    if (item.code === targetCode) {
                                        return newPath;
                                    }
                                    if (item.children) {
                                        const result = findCategoryPath(item.children, targetCode, newPath);
                                        if (result) return result;
                                    }
                                }
                                return null;
                            };

                            const path = findCategoryPath(this.treeData, this.defaultCategory);
                            // console.log(path, 'path');

                            if (path) {
                                this.categoryIds = path;
                                this.searchParams.categoryId = path[path.length - 1];
                                this.categoryIdDisable = true;
                            }
                        }
                    }
                });
            },
            getStockTypeListRequest() {
                return systemBusinessDictPage({ categoryCode: 'STOCK_TYPE' }).then(res => {
                    if (res.data.status === 200) {
                        this.typeList = res.data.res;
                    }
                });
            },
            async getDependentData() {
                this.tableLoading = true;
                // this.$set(this.searchParams, 'typeNameOrCode', this.defaultStockType);
                // this.$set(this.searchParams, 'categoryId', JSON.parse(JSON.stringify(this.categoryIds)));
                // this.categoryIdDisable = !this.categoryIds.length;
                await this.getTreeListRequest();
                await this.getStockTypeListRequest();
                await this.getListRequest();
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
